// index/pages/dailyCard/dailyCard.js
const { http } = require('../../../utils/http.js');
const storageUtil = require('../../../utils/storageUtil');

// 配置选项 - 可以在这里调整后端服务地址
const API_CONFIG = {
  // 后端服务地址 - 根据您的实际后端服务地址修改
  BASE_URL: 'http://localhost:8080', // 如果后端运行在8080端口，请修改这里
};

// 创建自定义的HTTP实例，使用页面配置的BASE_URL
const customHttp = new (require('../../../utils/http.js').HttpUtil)({
  BASE_URL: API_CONFIG.BASE_URL
});

Page({
  data: {
    points: 0, // 总积分
    consecutiveDays: 0, // 连续签到天数
    currentYear: 0, // 当前年份
    currentMonth: 0, // 当前月份
    currentDay: 0, // 当前日期
    weeks: [], // 日历数据
    isSignedToday: false, // 今天是否已签到
    signedDates: [], // 已签到的日期
    missedDates: [], // 未签到的日期
    loading: false, // 加载状态
    userId: null, // 用户ID
    userInfo: null // 用户信息
  },

  onLoad: function() {
    // 获取当前日期
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    this.setData({
      currentYear: year,
      currentMonth: month,
      currentDay: day
    });
    
    // 获取用户信息
    this.getUserInfo();
    
    // 生成日历
    this.generateCalendar(year, month);
    
    // 加载打卡数据
    this.loadCheckInData();
  },

  /**
   * 获取用户信息
   */
  getUserInfo() {
    // 从storageUtil获取用户信息
    const userInfo = storageUtil.getUserInfo();
    const token = storageUtil.getToken();
    
    if (userInfo && userInfo.userId) {
      this.setData({ 
        userId: userInfo.userId,
        userInfo: userInfo
      });
      console.log('获取到用户信息:', userInfo);
    } else if (token) {
      // 如果有token但没有用户信息，尝试从token中解析用户ID
      // 这里可以根据实际情况调整
      console.log('有token但无用户信息，使用默认用户ID');
      this.setData({ userId: 1 });
    } else {
      console.log('未获取到用户信息，使用默认用户ID');
      this.setData({ userId: 1 });
    }
  },

  /**
   * 加载打卡数据
   */
  loadCheckInData() {
    this.setData({ loading: true });
    
    // 获取token
    const token = storageUtil.getToken();
    
    if (!token) {
      console.log('未获取到token，使用默认数据');
      this.setDefaultCheckInData();
      this.setData({ loading: false });
      return;
    }
    
    // 使用一日一练的接口来获取打卡记录
    const params = {
      pageNum: 1,
      pageSize: 100, // 获取足够多的记录
      userId: this.data.userId // 确保只获取当前用户的记录
    };
    
    console.log('请求打卡数据，参数:', params);
    
    // 使用一日一练的接口路径
    customHttp.get('/hyg/practice/list', params)
      .then(res => {
        console.log('打卡数据获取成功:', res);
        
        if (res.rows && Array.isArray(res.rows)) {
          this.processCheckInData(res.rows);
        } else if (res.data && Array.isArray(res.data)) {
          // 如果返回的是data字段
          this.processCheckInData(res.data);
        } else {
          console.log('没有打卡数据或数据格式异常:', res);
          this.setDefaultCheckInData();
        }
      })
      .catch(err => {
        console.error('获取打卡数据失败:', err);
        
        // 显示错误信息
        let errorMessage = '获取打卡数据失败';
        if (err.code === 404) {
          errorMessage = '接口不存在，请检查后端服务';
        } else if (err.code === 500) {
          errorMessage = '服务器错误，请稍后重试';
        } else if (err.code === 403) {
          errorMessage = '权限不足，请检查登录状态';
        }
        
        wx.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
        
        // 使用默认数据
        this.setDefaultCheckInData();
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  /**
   * 设置默认打卡数据（当接口失败时使用）
   */
  setDefaultCheckInData() {
    // 设置一些默认的打卡数据用于演示
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
    
    // 随机生成一些打卡记录
    const signedDates = [];
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth() + 1;
    
    for (let day = 1; day <= today.getDate(); day++) {
      if (Math.random() > 0.3) { // 70%的概率打卡
        const dateStr = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
        signedDates.push(dateStr);
      }
    }
    
    // 计算连续打卡天数
    const consecutiveDays = this.calculateConsecutiveDays(signedDates);
    
    // 计算积分（每天10分）
    const points = signedDates.length * 10;
    
    // 检查今天是否已打卡
    const isSignedToday = signedDates.includes(todayStr);
    
    this.setData({
      signedDates: signedDates,
      consecutiveDays: consecutiveDays,
      points: points,
      isSignedToday: isSignedToday
    });
    
    // 重新生成日历
    this.generateCalendar(this.data.currentYear, this.data.currentMonth);
  },

  /**
   * 处理打卡数据
   */
  processCheckInData(checkInList) {
    const signedDates = [];
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth() + 1;
    
    console.log('处理打卡数据，用户ID:', this.data.userId);
    console.log('原始打卡数据:', checkInList);
    
    // 处理打卡数据，确保只处理当前用户的记录
    checkInList.forEach(item => {
      // 检查是否是当前用户的记录
      if (item.userId && item.userId.toString() !== this.data.userId.toString()) {
        console.log('跳过其他用户记录:', item.userId, '当前用户:', this.data.userId);
        return;
      }
      
      if (item.practiceDate) {
        const checkInDate = new Date(item.practiceDate);
        const year = checkInDate.getFullYear();
        const month = checkInDate.getMonth() + 1;
        const day = checkInDate.getDate();
        
        // 只处理当前年月的打卡记录
        if (year === currentYear && month === currentMonth) {
          const dateStr = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
          signedDates.push(dateStr);
        }
      }
    });
    
    console.log('过滤后的打卡日期:', signedDates);
    
    // 计算连续打卡天数
    const consecutiveDays = this.calculateConsecutiveDays(signedDates);
    
    // 计算积分（每天10分）
    const points = signedDates.length * 10;
    
    // 检查今天是否已打卡
    const todayStr = `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}-${currentDate.getDate() < 10 ? '0' + currentDate.getDate() : currentDate.getDate()}`;
    const isSignedToday = signedDates.includes(todayStr);
    
    this.setData({
      signedDates: signedDates,
      consecutiveDays: consecutiveDays,
      points: points,
      isSignedToday: isSignedToday
    });
    
    // 重新生成日历
    this.generateCalendar(this.data.currentYear, this.data.currentMonth);
  },

  /**
   * 计算连续打卡天数
   */
  calculateConsecutiveDays(signedDates) {
    if (signedDates.length === 0) return 0;
    
    const today = new Date();
    let consecutiveDays = 0;
    let currentDate = new Date(today);
    
    // 从今天开始往前检查
    while (true) {
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      const day = currentDate.getDate();
      const dateStr = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
      
      if (signedDates.includes(dateStr)) {
        consecutiveDays++;
        // 往前一天
        currentDate.setDate(currentDate.getDate() - 1);
      } else {
        break;
      }
    }
    
    return consecutiveDays;
  },

  // 生成日历数据
  generateCalendar: function(year, month) {
    // 获取当月第一天是星期几（0-6，0是周日）
    const firstDay = new Date(year, month - 1, 1).getDay();
    // 获取当月天数
    const daysInMonth = new Date(year, month, 0).getDate();
    // 获取上个月天数
    const daysInLastMonth = new Date(year, month - 1, 0).getDate();
    
    // 计算日历开始显示的日期（可能包含上个月的最后几天）
    let startDay = daysInLastMonth - firstDay + 2;
    if (firstDay === 1) startDay = 1; // 如果第一天是周一，不需要显示上个月的日期
    
    const weeks = [];
    let week = [];
    
    // 添加上个月的日期
    if (firstDay > 1) {
      for (let i = 1; i < firstDay; i++) {
        const day = startDay++;
        week.push({
          day: day,
          isCurrentMonth: false,
          isSigned: false,
          isMissed: false,
          isToday: false
        });
      }
    }
    
    // 添加当月的日期
    let dayCount = 1;
    while (dayCount <= daysInMonth) {
      // 如果一周已满，添加到周数组并开始新的一周
      if (week.length === 7) {
        weeks.push(week);
        week = [];
      }
      
      const dateStr = `${year}-${month < 10 ? '0' + month : month}-${dayCount < 10 ? '0' + dayCount : dayCount}`;
      const isSigned = this.data.signedDates.includes(dateStr);
      const isToday = dayCount === this.data.currentDay && month === this.data.currentMonth && year === this.data.currentYear;
      
      week.push({
        day: dayCount,
        isCurrentMonth: true,
        isSigned: isSigned,
        isMissed: false,
        isToday: isToday
      });
      
      dayCount++;
    }
    
    // 添加下个月的日期
    let nextMonthDay = 1;
    while (week.length < 7) {
      week.push({
        day: nextMonthDay++,
        isCurrentMonth: false,
        isSigned: false,
        isMissed: false,
        isToday: false
      });
    }
    
    // 添加最后一周
    weeks.push(week);
    
    this.setData({
      weeks: weeks
    });
  },

  // 签到按钮点击事件
  handleSignIn: function() {
    if (this.data.isSignedToday || this.data.loading) {
      return;
    }
    
    this.setData({ loading: true });
    
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    const dateStr = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    
    // 调用后端打卡接口 - 使用一日一练的接口
    const checkInData = {
      userId: this.data.userId,
      practiceDate: dateStr,
      questionCount: 0, // 默认刷题数量
      studyTime: 0, // 默认学习时间
      del: 1 // 有效记录
    };
    
    console.log('发送打卡数据:', checkInData);
    
    // 使用一日一练的接口路径
    customHttp.post('/hyg/practice', checkInData)
      .then(res => {
        console.log('打卡成功:', res);
        
        // 更新本地状态
        const signedDates = [...this.data.signedDates, dateStr];
        const points = this.data.points + 10;
        const consecutiveDays = this.data.consecutiveDays + 1;
        
        this.setData({
          isSignedToday: true,
          signedDates: signedDates,
          points: points,
          consecutiveDays: consecutiveDays
        });
        
        // 重新生成日历
        this.generateCalendar(this.data.currentYear, this.data.currentMonth);
        
        wx.showToast({
          title: '打卡成功 +10积分',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('打卡失败:', err);
        
        let errorMessage = '打卡失败';
        if (err.code === 400) {
          errorMessage = '今天已经打卡了';
        } else if (err.code === 404) {
          errorMessage = '接口不存在，请检查后端服务';
        } else if (err.code === 500) {
          errorMessage = '服务器错误，请稍后重试';
        } else if (err.code === 403) {
          errorMessage = '权限不足，请检查登录状态';
        }
        
        wx.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadCheckInData();
    wx.stopPullDownRefresh();
  }
});